package com.hyb.algorithm.data.struct.queue;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 *
 * LRU 算法
 * @Author: huyanbing
 * @Date: 2021/9/3 2:02 下午
 */

public class LRUCache3 {

    int capactiy;
    HashMap<Integer, Node> map = new HashMap<>();
    Node head = null;
    Node end = null;

    public LRUCache3(int capactiy) {
        this.capactiy = capactiy;
    }

    public int get(int key) {

        if (map.containsKey(key)) {
            //将节点放入第一个
            Node node = map.get(key);
            remove(node);
            map.put(key, node);
            setHead(node);
            return node.val;
        } else {
            return -1;
        }
    }


    private void remove(Node node) {
        if (node.prev != null) {
            node.prev.next = node.next;
        } else {
            head = node.next;
        }

        if (node.next != null) {
            node.next.prev = node.prev.prev;
        } else {
            end = node.prev;
        }
    }


    private void setHead(Node node) {
        node.next = head;
        node.prev = null;

        if (head != null) {
            head.prev = node;
        }

        head = node;

        if (end == null) {
            end = head;
        }
    }


    public void set(int key, int val) {
        if (map.containsKey(key)) {
            Node old = map.get(key);
            old.val = val;
            remove(old);
            setHead(old);
        } else {
            Node created = new Node(key, val);
            if (map.size() >= capactiy) {
                map.remove(end.key);
                remove(end);
                setHead(created);
            } else {
                setHead(created);
            }
            map.put(key, created);
        }
    }

}



